﻿using System;
using System.Collections.Generic;
using System.Linq;
using Crawler.ApplicationServices;
using Crawler.Domain.DataEntities;
using Crawler.Domain.DataEntities.Extracted;
using Crawler.DomainServices.Processors;
using HtmlAgilityPack;
using log4net;

namespace Crawler.ContentProcessors.Yify
{
	internal class YifySubtitleProcessor : IYifySubtitleProcessor
	{
		private static readonly ILog Logger = LogManager.GetLogger("AppLogger");
		private readonly IHtmlParserHelper _parserHelper;
		private readonly IRequestsHelper _requestsHelper;

		public YifySubtitleProcessor(IHtmlParserHelper parserHelper, IRequestsHelper requestsHelper)
		{
			_parserHelper = parserHelper;
			_requestsHelper = requestsHelper;
			_requestsHelper.SetRetriesUpTo(5);
		}

		public IList<SubtitleFile> GetSubtitlesFor(string id)
		{
			return new SubtitleFile[0];
			//TODO: this is done in a different crawling

			var result = new List<SubtitleFile>();
			
			string html;
			string urlPage = GetUrlPage(id);
			try
			{
				html = _requestsHelper.GetPageHtmlText(urlPage);
			}
			catch (Exception ex)
			{
				Logger.WarnFormat("Could not download page {0}. {1}", urlPage, ex);
				return result;
			}

			var doc = new HtmlDocument();
			doc.LoadHtml(html);
			HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//*[@class='high-rating']");

			if (nodes != null)
			{
				result.AddRange(nodes.Select(node => GetSubtitle(node, id)));
			}

			return result;
		}

		private SubtitleFile GetSubtitle(HtmlNode node, string id)
		{
			return new SubtitleFile
			{
				Language = _parserHelper.GetInnerTextOfSingleNode(node, "//*[@class='subtitle-page']//span[2]"),
				UrlSubtitle = GetUriSubtitle(node).AbsoluteUri,
				FromUrl = GetUrlPage(id),
				UtcCrawled = DateTime.UtcNow
			};
		}

		private Uri GetUriSubtitle(HtmlNode node)
		{
			var url = new Uri(new Uri(@"http://www.yifysubtitles.com/"),
				_parserHelper.GetAttributeValueOfSingleNode(node, "//*[@class='subtitle-download']", "href"));
			string content = _requestsHelper.GetPageHtmlText(url.AbsoluteUri);
			var d = new HtmlDocument();
			d.LoadHtml(content);
			string attributeValueOfSingleNode = _parserHelper.GetAttributeValueOfSingleNode(d.DocumentNode,
				"//*[@class='stats']/a[1]", "href");
			return new Uri(attributeValueOfSingleNode);
		}


		private static string GetUrlPage(string imdbId)
		{
			return string.Format("http://www.yifysubtitles.com/movie-imdb/{0}", imdbId);
		}
	}
}